// SPAM3-UK Ford汽车信息页面 - 主要功能脚本

// 全局状态管理
const AppState = {
    vehicles: [],
    filteredVehicles: [],
    displayedVehicles: [],
    isLoading: false,
    isScraping: false,
    pagination: {
        currentPage: 1,
        pageSize: 10,
        totalPages: 0,
        totalRecords: 0
    },
    currentFilters: {
        make: '',
        model: '',
        fuelType: '',
        bodyStyle: '',
        minPrice: '',
        maxPrice: ''
    }
};

// API配置
const API_CONFIG = {
    baseUrl: '/api',
    endpoints: {
        vehicles: '/vehicles',
        trims: '/get_trims',
        scrapeTrims: '/scrape_trims'
    }
};

// 初始化应用
document.addEventListener('DOMContentLoaded', function() {
    console.log('🚀 SPAM3-UK应用初始化');
    initializeApp();
});

/**
 * 应用初始化
 */
function initializeApp() {
    setupEventListeners();
    loadVehicles();
    updateStats();
}

/**
 * 设置事件监听器
 */
function setupEventListeners() {
    // 筛选器事件
    const filterInputs = document.querySelectorAll('.filters input, .filters select');
    filterInputs.forEach(input => {
        input.addEventListener('change', handleFilterChange);
        input.addEventListener('input', debounce(handleFilterChange, 300));
    });

    // 清除筛选器
    const clearFiltersBtn = document.getElementById('clearFilters');
    if (clearFiltersBtn) {
        clearFiltersBtn.addEventListener('click', clearFilters);
    }

    // 刷新数据
    const refreshBtn = document.getElementById('refreshData');
    if (refreshBtn) {
        refreshBtn.addEventListener('click', handleRefreshData);
    }

    // 分页事件
    const prevPageBtn = document.getElementById('prevPage');
    const nextPageBtn = document.getElementById('nextPage');
    const pageSizeSelect = document.getElementById('pageSize');
    
    if (prevPageBtn) {
        prevPageBtn.addEventListener('click', prevPage);
    }
    if (nextPageBtn) {
        nextPageBtn.addEventListener('click', nextPage);
    }
    if (pageSizeSelect) {
        pageSizeSelect.addEventListener('change', changePageSize);
    }

    // 模态框关闭事件
    window.addEventListener('click', function(event) {
        const modal = document.getElementById('trimModal');
        if (event.target === modal) {
            closeTrimModal();
        }
    });

    // ESC键关闭模态框
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            closeTrimModal();
        }
    });
}

/**
 * 防抖函数
 */
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

/**
 * 处理筛选器变化
 */
function handleFilterChange() {
    // 更新当前筛选器状态
    AppState.currentFilters.make = document.getElementById('makeFilter').value;
    AppState.currentFilters.model = document.getElementById('modelFilter').value;
    AppState.currentFilters.fuelType = document.getElementById('fuelTypeFilter').value;
    AppState.currentFilters.bodyStyle = document.getElementById('bodyStyleFilter').value;
    AppState.currentFilters.minPrice = document.getElementById('minPrice').value;
    AppState.currentFilters.maxPrice = document.getElementById('maxPrice').value;

    // 应用筛选
    applyFilters();
    updateStats();
}

/**
 * 应用筛选器
 */
function applyFilters() {
    const filters = AppState.currentFilters;
    
    AppState.filteredVehicles = AppState.vehicles.filter(vehicle => {
        // Make筛选
        if (filters.make && vehicle.make !== filters.make) {
            return false;
        }
        
        // Model筛选
        if (filters.model && vehicle.model !== filters.model) {
            return false;
        }
        
        // Fuel Type筛选
        if (filters.fuelType && vehicle.fuel_type !== filters.fuelType) {
            return false;
        }
        
        // Body Style筛选
        if (filters.bodyStyle && vehicle.body_style !== filters.bodyStyle) {
            return false;
        }
        
        // 价格范围筛选
        const price = parseFloat(vehicle.price_from) || 0;
        if (filters.minPrice && price < parseFloat(filters.minPrice)) {
            return false;
        }
        if (filters.maxPrice && price > parseFloat(filters.maxPrice)) {
            return false;
        }
        
        return true;
    });

    displayVehicles(AppState.filteredVehicles);
}

/**
 * 清除筛选器
 */
function clearFilters() {
    // 重置筛选器表单
    document.getElementById('makeFilter').value = '';
    document.getElementById('modelFilter').value = '';
    document.getElementById('fuelTypeFilter').value = '';
    document.getElementById('bodyStyleFilter').value = '';
    document.getElementById('minPrice').value = '';
    document.getElementById('maxPrice').value = '';

    // 重置状态
    AppState.currentFilters = {
        make: '',
        model: '',
        fuelType: '',
        bodyStyle: '',
        minPrice: '',
        maxPrice: ''
    };

    // 显示所有车辆
    AppState.filteredVehicles = AppState.vehicles ? [...AppState.vehicles] : [];
    displayVehicles(AppState.filteredVehicles);
    updateStats();
}

/**
 * 刷新数据 - 修复Issue #013
 */
function handleRefreshData() {
    // 防止重复点击
    if (AppState.isLoading) {
        console.log('⚠️ 数据正在加载中，请稍候...');
        return;
    }

    const refreshBtn = document.getElementById('refreshData');
    if (refreshBtn) {
        refreshBtn.disabled = true;
        refreshBtn.textContent = '刷新中...';
    }

    loadVehicles().finally(() => {
        if (refreshBtn) {
            refreshBtn.disabled = false;
            refreshBtn.textContent = '刷新数据';
        }
    });
}

/**
 * 加载车辆数据
 */
async function loadVehicles() {
    if (AppState.isLoading) {
        console.log('⚠️ 数据正在加载中，跳过重复请求');
        return;
    }

    AppState.isLoading = true;
    
    try {
        showLoadingState();
        
        const response = await fetch(API_CONFIG.baseUrl + API_CONFIG.endpoints.vehicles + 
            `?page=${AppState.pagination.currentPage}&page_size=${AppState.pagination.pageSize}`);
        
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        const data = await response.json();
        
        if (data.error) {
            throw new Error(data.error);
        }
        
        // 处理API响应格式：{code, message, data, total}
        let vehiclesArray = [];
        if (data.data && Array.isArray(data.data)) {
            vehiclesArray = data.data;
        } else if (Array.isArray(data)) {
            // 兼容直接返回数组的情况
            vehiclesArray = data;
        } else {
            console.warn('⚠️ API返回数据格式异常:', data);
            vehiclesArray = [];
        }
        
        AppState.vehicles = vehiclesArray;
        AppState.filteredVehicles = [...vehiclesArray];
        
        // 更新分页信息
        if (data.total !== undefined) {
            AppState.pagination.totalRecords = data.total;
            AppState.pagination.totalPages = Math.ceil(data.total / AppState.pagination.pageSize);
        }
        
        displayVehicles(AppState.filteredVehicles);
        updateFilterOptions();
        updateStats();
        updatePagination();
        hideLoadingState();
        
        console.log(`✅ 成功加载 ${vehiclesArray.length} 辆车辆数据`);
        
        // 如果API返回了total字段，也记录它
        if (data.total) {
            console.log(`📊 API报告总数: ${data.total} 辆车辆`);
        }
        
    } catch (error) {
        console.error('❌ 加载车辆数据失败:', error);
        showError('加载车辆数据失败: ' + error.message);
        hideLoadingState();
    } finally {
        AppState.isLoading = false;
    }
}

/**
 * 显示车辆列表
 */
function displayVehicles(vehicles) {
    const container = document.getElementById('vehicleGrid');
    if (!container) return;

    if (vehicles.length === 0) {
        container.innerHTML = '<div class="text-center" style="grid-column: 1/-1; padding: 40px;"><h3>未找到符合条件的车辆</h3></div>';
        return;
    }

    container.innerHTML = vehicles.map(vehicle => `
        <div class="vehicle-card">
            ${vehicle.image_url ? `<img src="${vehicle.image_url}" alt="${vehicle.model}" class="vehicle-image" onerror="this.style.display='none'">` : ''}
            <div class="vehicle-title">${vehicle.make} ${vehicle.model}</div>
            
            <div class="vehicle-info"><strong>价格:</strong> £${vehicle.price_from ? parseFloat(vehicle.price_from).toLocaleString() : 'N/A'}</div>
            <div class="vehicle-info"><strong>燃料类型:</strong> ${vehicle.fuel_type || 'N/A'}</div>
            <div class="vehicle-info"><strong>车身类型:</strong> ${vehicle.body_style || 'N/A'}</div>
            <div class="vehicle-info"><strong>变速箱:</strong> ${vehicle.transmission || 'N/A'}</div>
            <div class="trim-actions mt-15">
                <button onclick="showTrims('${vehicle.model}')" class="trim-btn">
                    🔍 查看配置
                </button>
                <button onclick="scrapeTrims('${vehicle.model}')" class="scrape-btn" ${AppState.isScraping ? 'disabled' : ''}>
                    📥 抓取配置
                </button>
            </div>
        </div>
    `).join('');
}

/**
 * 更新筛选器选项
 */
function updateFilterOptions() {
    const vehicles = AppState.vehicles;
    
    updateSelectOptions('makeFilter', [...new Set(vehicles.map(v => v.make))].filter(Boolean));
    updateSelectOptions('modelFilter', [...new Set(vehicles.map(v => v.model))].filter(Boolean));
    updateSelectOptions('fuelTypeFilter', [...new Set(vehicles.map(v => v.fuel_type))].filter(Boolean));
    updateSelectOptions('bodyStyleFilter', [...new Set(vehicles.map(v => v.body_style))].filter(Boolean));
}

/**
 * 更新下拉框选项
 */
function updateSelectOptions(selectId, options) {
    const select = document.getElementById(selectId);
    if (!select) return;
    
    const currentValue = select.value;
    const defaultOption = select.querySelector('option[value=""]');
    
    select.innerHTML = '';
    if (defaultOption) {
        select.appendChild(defaultOption.cloneNode(true));
    }
    
    options.sort().forEach(option => {
        const optionElement = document.createElement('option');
        optionElement.value = option;
        optionElement.textContent = option;
        select.appendChild(optionElement);
    });
    
    if (currentValue && options.includes(currentValue)) {
        select.value = currentValue;
    }
}

/**
 * 更新统计信息
 */
function updateStats() {
    const vehicles = AppState.filteredVehicles;
    
    document.getElementById('totalVehicles').textContent = vehicles.length;
    document.getElementById('avgPrice').textContent = calculateAveragePrice(vehicles);
    document.getElementById('uniqueModels').textContent = [...new Set(vehicles.map(v => v.model))].length;
    
    // 燃料类型分布
    const fuelTypes = vehicles.reduce((acc, v) => {
        const key = (v.fuel_type || 'Unknown');
        acc[key] = (acc[key] || 0) + 1;
        return acc;
    }, {});
    
    const mostCommonFuel = Object.entries(fuelTypes).sort((a, b) => b[1] - a[1])[0];
    document.getElementById('fuelTypeStats').textContent = mostCommonFuel ? `${mostCommonFuel[0]} (${mostCommonFuel[1]})` : 'N/A';
}

/**
 * 计算平均价格
 */
function calculateAveragePrice(vehicles) {
    const validPrices = vehicles
        .map(v => parseFloat(v.price_from))
        .filter(price => !isNaN(price) && price > 0);
    
    if (validPrices.length === 0) return 'N/A';
    
    const avg = validPrices.reduce((sum, price) => sum + price, 0) / validPrices.length;
    return `£${Math.round(avg).toLocaleString()}`;
}

/**
 * 显示加载状态
 */
function showLoadingState() {
    const container = document.getElementById('vehicleGrid');
    if (container) {
        container.innerHTML = '<div class="loading text-center" style="grid-column: 1/-1;">正在加载车辆数据</div>';
    }
}

/**
 * 隐藏加载状态
 */
function hideLoadingState() {
    // 加载状态将被displayVehicles替换
}

/**
 * 显示错误信息
 */
function showError(message) {
    const container = document.getElementById('vehicleGrid');
    if (container) {
        container.innerHTML = `<div class="error text-center" style="grid-column: 1/-1;">${message}</div>`;
    }
}

/**
 * 显示成功信息
 */
function showSuccess(message) {
    // 创建临时成功提示
    const successDiv = document.createElement('div');
    successDiv.className = 'success';
    successDiv.textContent = message;
    
    const container = document.querySelector('.container');
    if (container) {
        container.insertBefore(successDiv, container.firstChild);
        
        // 3秒后自动移除
        setTimeout(() => {
            if (successDiv.parentNode) {
                successDiv.parentNode.removeChild(successDiv);
            }
        }, 3000);
    }
}

/**
 * 更新分页显示
 */
function updatePagination() {
    const pageInfo = document.getElementById('pageInfo');
    const pageNumbers = document.getElementById('pageNumbers');
    const prevButton = document.getElementById('prevPage');
    const nextButton = document.getElementById('nextPage');
    
    if (!pageInfo || !pageNumbers || !prevButton || !nextButton) return;
    
    const { currentPage, pageSize, totalRecords, totalPages } = AppState.pagination;
    const startRecord = (currentPage - 1) * pageSize + 1;
    const endRecord = Math.min(currentPage * pageSize, totalRecords);
    
    // 更新信息显示
    pageInfo.textContent = `显示第 ${startRecord}-${endRecord} 条，共 ${totalRecords} 条记录`;
    
    // 更新按钮状态
    prevButton.disabled = currentPage <= 1;
    nextButton.disabled = currentPage >= totalPages;
    
    // 生成页码按钮
    pageNumbers.innerHTML = '';
    
    if (totalPages <= 1) return;
    
    // 计算显示的页码范围
    let startPage = Math.max(1, currentPage - 2);
    let endPage = Math.min(totalPages, currentPage + 2);
    
    // 确保至少显示5个页码（如果总页数>=5）
    if (endPage - startPage < 4) {
        if (startPage === 1) {
            endPage = Math.min(totalPages, startPage + 4);
        } else {
            startPage = Math.max(1, endPage - 4);
        }
    }
    
    // 生成页码按钮
    for (let i = startPage; i <= endPage; i++) {
        const pageBtn = document.createElement('button');
        pageBtn.className = `page-number ${i === currentPage ? 'active' : ''}`;
        pageBtn.textContent = i;
        pageBtn.onclick = () => goToPage(i);
        pageNumbers.appendChild(pageBtn);
    }
}

/**
 * 跳转到指定页面
 */
function goToPage(page) {
    if (page < 1 || page > AppState.pagination.totalPages) return;
    
    AppState.pagination.currentPage = page;
    loadVehicles();
}

/**
 * 上一页
 */
function prevPage() {
    if (AppState.pagination.currentPage > 1) {
        goToPage(AppState.pagination.currentPage - 1);
    }
}

/**
 * 下一页
 */
function nextPage() {
    if (AppState.pagination.currentPage < AppState.pagination.totalPages) {
        goToPage(AppState.pagination.currentPage + 1);
    }
}

/**
 * 更改每页显示数量
 */
function changePageSize() {
    const pageSizeSelect = document.getElementById('pageSize');
    if (!pageSizeSelect) return;
    
    AppState.pagination.pageSize = parseInt(pageSizeSelect.value);
    AppState.pagination.currentPage = 1; // 重置到第一页
    AppState.pagination.totalPages = Math.ceil(AppState.pagination.totalRecords / AppState.pagination.pageSize);
    
    loadVehicles();
}

// 将主要函数添加到全局作用域，供HTML调用
window.AppState = AppState;
window.loadVehicles = loadVehicles;
window.handleRefreshData = handleRefreshData;
window.clearFilters = clearFilters;
